package juc;

public class SaleJUCTest
{
    public static void main(String[] args)
    {
        Clerk clerk = new Clerk();
        Sale sale = new Sale(clerk);
        GetProduct getProduct = new GetProduct(clerk);
        new Thread(sale,"消费者A").start();
        new Thread(sale,"消费者B").start();
        new Thread(getProduct, "生产者A").start();
        new Thread(getProduct,"生产者B").start();
    }
}
class Sale implements Runnable{

    private Clerk clerk;

    public Sale(Clerk clerk)
    {
        this.clerk = clerk;
    }
    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            //卖出产品
            clerk.saleProduct();
        }
    }
}
class GetProduct implements Runnable{

    private Clerk clerk;

    public GetProduct(Clerk clerk)
    {
        this.clerk = clerk;
    }
    @Override
    public void run()
    {
        for (int i = 0; i < 20; i++)
        {
            try
            {
                Thread.sleep(200);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            clerk.getProduct();
        }
    }
}

class Clerk{

     private int product = 0;

    public synchronized void getProduct()
    {
        while (product >= 1)
        {
            System.out.println("产品已满！");
            try
            {
                this.wait();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"===="+ ++product);
        this.notifyAll();
    }

    public synchronized void saleProduct()
    {
        while (product <= 0)
        {
            System.out.println("缺货中.....");
            try
            {
                this.wait();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"===="+ --product);
        this.notifyAll();
    }

}
